<template>
  <div class="login-page">
    <div class="login-card">
      <!-- 左侧登录表单 -->
      <div class="login-form-wrapper">
        <!-- 站点 Logo 与标题 -->
        <div class="site-header">
          <div class="logo-box">
            <img src="/img/logo.png" alt="Logo" loading="lazy" />
          </div>
          <div class="site-title">国际精卵库注册中心</div>
        </div>

        <div class="title-box">
          <h2 class="form-title">登录账号</h2>
          <lang-select />
        </div>
        <!-- 装饰线 -->
        <div class="divider">
          <div class="divider-short"></div>
          <div class="divider-long"></div>
        </div>

        <!-- 登录表单 -->
        <el-form :model="loginForm" :rules="loginRules" ref="loginRef" class="login-form">
          <el-form-item v-if="tenantEnabled" prop="tenantId">
            <label class="form-label">公司名称</label>
            <el-select
              class="form-input"
              v-model="loginForm.tenantId"
              size="large"
              filterable
              :placeholder="proxy.$t('login.selectPlaceholder')"
              style="width: 100%"
            >
              <el-option v-for="item in tenantList" :key="item.tenantId" :label="item.companyName" :value="item.tenantId"></el-option>
              <template #prefix><svg-icon icon-class="company" class="el-input__icon input-icon" /></template>
            </el-select>
          </el-form-item>
          <!-- 用户名 -->
          <el-form-item prop="username">
            <label class="form-label">用户名</label>
            <el-input v-model="loginForm.username" :placeholder="proxy.$t('login.username')" class="form-input" size="large">
              <template #prefix>
                <LazyUserFilled class="input-icon" />
              </template>
            </el-input>
          </el-form-item>

          <!-- 密码 -->
          <el-form-item prop="password">
            <label class="form-label">密码</label>
            <el-input
              v-model="loginForm.password"
              type="password"
              :placeholder="proxy.$t('login.password')"
              class="form-input"
              size="large"
              show-password
              @keyup.enter="handleLogin"
            >
              <template #prefix>
                <LazyLock class="input-icon" />
              </template>
            </el-input>
          </el-form-item>
          <el-form-item v-if="captchaEnabled" prop="code">
            <label class="form-label">验证码</label>
            <div class="code_box">
              <el-input
                v-model="loginForm.code"
                :placeholder="proxy.$t('login.code')"
                class="form-input code_input"
                size="large"
                style="width: 63%"
                @keyup.enter="handleLogin"
              >
              </el-input>
              <div class="login-code">
                <img :src="codeUrl" class="login-code-img" @click="getCode" />
              </div>
            </div>
          </el-form-item>
          <div class="rember">
            <el-checkbox v-model="loginForm.rememberMe" style="margin: 0 0 25px 0">{{ proxy.$t('login.rememberPassword') }}</el-checkbox>
            <el-form-item style="float: right">
              <el-button circle :title="proxy.$t('login.social.wechat')" @click="doSocialLogin('wechat')">
                <svg-icon icon-class="wechat" />
              </el-button>
              <el-button circle :title="proxy.$t('login.social.maxkey')" @click="doSocialLogin('maxkey')">
                <svg-icon icon-class="maxkey" />
              </el-button>
              <el-button circle :title="proxy.$t('login.social.topiam')" @click="doSocialLogin('topiam')">
                <svg-icon icon-class="topiam" />
              </el-button>
              <el-button circle :title="proxy.$t('login.social.gitee')" @click="doSocialLogin('gitee')">
                <svg-icon icon-class="gitee" />
              </el-button>
              <el-button circle :title="proxy.$t('login.social.github')" @click="doSocialLogin('github')">
                <svg-icon icon-class="github" />
              </el-button>
            </el-form-item>
          </div>
          <!-- 登录按钮 -->
          <el-button type="primary" :loading="loading" class="submit-btn" @click="handleLogin">
            <span v-if="!loading">{{ proxy.$t('login.login') }}</span>
            <span v-else>{{ proxy.$t('login.logging') }}</span>
          </el-button>
          <div v-if="register" style="float: right">
            <router-link class="link-type" :to="'/register'">{{ proxy.$t('login.switchRegisterPage') }}</router-link>
          </div>
        </el-form>

        <!-- 分割线 -->
        <div class="section-divider"></div>

        <!-- 额外入口 -->
        <div class="extra-links">
          <div class="link-row">
            <span class="link-text">如果您是新意向父母，想要查看我们的国际精卵者库。</span>
            <router-link to="/questionnaire/parents-to-be">
              <el-button type="text" class="link-btn">请点击此处</el-button>
            </router-link>
          </div>
          <div class="link-row">
            <span class="link-text">如果您是新捐献者，想要申请。</span>
            <el-button type="text" class="link-btn" @click="showDialog = true"> 请点击此处 </el-button>
          </div>
        </div>
      </div>
      <!-- 捐献者选择弹窗（按需显示） -->
      <el-dialog v-model="showDialog" width="33rem" :show-close="false" custom-class="donor-dialog">
        <div class="donor-dialog-body">
          <div class="donor-options">
            <!-- 捐卵入口 -->
            <div class="donor-option">
              <router-link to="/questionnaire/egg_donors" class="donor-card egg">
                <img src="/img/801011157ca5b01cbbf7e22fff71cd3e.png" loading="lazy" alt="捐卵入口" />
              </router-link>
              <router-link to="/questionnaire/egg_donors" class="donor-label egg"> 我要捐卵 </router-link>
            </div>

            <!-- 捐精入口 -->
            <div class="donor-option">
              <router-link to="/questionnaire/sperm_donors" class="donor-card sperm">
                <img src="/img/be9a0ff5de013bc840b1a88891e9088f.png" loading="lazy" alt="捐精入口" />
              </router-link>
              <router-link to="/questionnaire/sperm_donors" class="donor-label sperm"> 我要捐精 </router-link>
            </div>
          </div>
        </div>
      </el-dialog>

      <!-- 右侧背景图片（大屏显示） -->
      <div class="login-bg">
        <img src="/img/414866d2793c4cc8dd5843b677d7379b.png" alt="登录背景图" loading="lazy" />
      </div>
    </div>
  </div>
  <!-- <div class="login">
    <el-form ref="loginRef" :model="loginForm" :rules="loginRules" class="login-form">
      <div class="title-box">
        <h3 class="title">{{ title }}</h3>
        <lang-select />
      </div>
      <el-form-item v-if="tenantEnabled" prop="tenantId">
        <el-select v-model="loginForm.tenantId" filterable :placeholder="proxy.$t('login.selectPlaceholder')" style="width: 100%">
          <el-option v-for="item in tenantList" :key="item.tenantId" :label="item.companyName" :value="item.tenantId"></el-option>
          <template #prefix><svg-icon icon-class="company" class="el-input__icon input-icon" /></template>
        </el-select>
      </el-form-item>
      <el-form-item prop="username">
        <el-input v-model="loginForm.username" type="text" size="large" auto-complete="off" :placeholder="proxy.$t('login.username')">
          <template #prefix><svg-icon icon-class="user" class="el-input__icon input-icon" /></template>
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          v-model="loginForm.password"
          type="password"
          size="large"
          auto-complete="off"
          :placeholder="proxy.$t('login.password')"
          @keyup.enter="handleLogin"
        >
          <template #prefix><svg-icon icon-class="password" class="el-input__icon input-icon" /></template>
        </el-input>
      </el-form-item>

      <el-form-item v-if="captchaEnabled" prop="code">
        <el-input
          v-model="loginForm.code"
          size="large"
          auto-complete="off"
          :placeholder="proxy.$t('login.code')"
          style="width: 63%"
          @keyup.enter="handleLogin"
        >
          <template #prefix><svg-icon icon-class="validCode" class="el-input__icon input-icon" /></template>
        </el-input>
        <div class="login-code">
          <img :src="codeUrl" class="login-code-img" @click="getCode" />
        </div>
      </el-form-item>
      <el-checkbox v-model="loginForm.rememberMe" style="margin: 0 0 25px 0">{{ proxy.$t('login.rememberPassword') }}</el-checkbox>
      <el-form-item style="float: right">
        <el-button circle :title="proxy.$t('login.social.wechat')" @click="doSocialLogin('wechat')">
          <svg-icon icon-class="wechat" />
        </el-button>
        <el-button circle :title="proxy.$t('login.social.maxkey')" @click="doSocialLogin('maxkey')">
          <svg-icon icon-class="maxkey" />
        </el-button>
        <el-button circle :title="proxy.$t('login.social.topiam')" @click="doSocialLogin('topiam')">
          <svg-icon icon-class="topiam" />
        </el-button>
        <el-button circle :title="proxy.$t('login.social.gitee')" @click="doSocialLogin('gitee')">
          <svg-icon icon-class="gitee" />
        </el-button>
        <el-button circle :title="proxy.$t('login.social.github')" @click="doSocialLogin('github')">
          <svg-icon icon-class="github" />
        </el-button>
      </el-form-item>
      <el-form-item style="width: 100%">
        <el-button :loading="loading" size="large" type="primary" style="width: 100%" @click.prevent="handleLogin">
          <span v-if="!loading">{{ proxy.$t('login.login') }}</span>
          <span v-else>{{ proxy.$t('login.logging') }}</span>
        </el-button>
        <div v-if="register" style="float: right">
          <router-link class="link-type" :to="'/register'">{{ proxy.$t('login.switchRegisterPage') }}</router-link>
        </div>
      </el-form-item>
    </el-form>
    <div class="el-login-footer">
      <span>Copyright © 2018-2025 All Rights Reserved.</span>
    </div>
  </div> -->
</template>

<script setup lang="ts">
import { getCodeImg, getTenantList } from '@/api/login';
import { authBinding } from '@/api/system/social/auth';
import { useUserStore } from '@/store/modules/user';
import { LoginData, TenantVO } from '@/api/types';
import { to } from 'await-to-js';
import { HttpStatus } from '@/enums/RespEnum';
import { useI18n } from 'vue-i18n';
import { getInfo } from '@/api/login';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const title = import.meta.env.VITE_APP_TITLE;
const userStore = useUserStore();
const router = useRouter();
const route = useRoute();
const { t } = useI18n();

const loginForm = ref<LoginData>({
  tenantId: '000000',
  username: 'admin',
  password: 'admin123',
  rememberMe: false,
  code: '',
  uuid: ''
} as LoginData);

const loginRules: ElFormRules = {
  tenantId: [{ required: true, trigger: 'blur', message: t('login.rule.tenantId.required') }],
  username: [{ required: true, trigger: 'blur', message: t('login.rule.username.required') }],
  password: [{ required: true, trigger: 'blur', message: t('login.rule.password.required') }],
  code: [{ required: true, trigger: 'change', message: t('login.rule.code.required') }]
};
const showDialog = ref(false);
const codeUrl = ref('');
const loading = ref(false);
// 验证码开关
const captchaEnabled = ref(true);
// 租户开关
const tenantEnabled = ref(true);

// 注册开关
const register = ref(false);
const redirect = ref('/');
const loginRef = ref<ElFormInstance>();
// 租户列表
const tenantList = ref<TenantVO[]>([]);

watch(
  () => router.currentRoute.value,
  (newRoute: any) => {
    redirect.value = newRoute.query && newRoute.query.redirect && decodeURIComponent(newRoute.query.redirect);
  },
  { immediate: true }
);

const handleLogin = () => {
  console.log(111111);
  loginRef.value?.validate(async (valid: boolean, fields: any) => {
    if (valid) {
      loading.value = true;
      // 勾选了需要记住密码设置在 localStorage 中设置记住用户名和密码
      if (loginForm.value.rememberMe) {
        localStorage.setItem('tenantId', String(loginForm.value.tenantId));
        localStorage.setItem('username', String(loginForm.value.username));
        localStorage.setItem('password', String(loginForm.value.password));
        localStorage.setItem('rememberMe', String(loginForm.value.rememberMe));
      } else {
        // 否则移除
        localStorage.removeItem('tenantId');
        localStorage.removeItem('username');
        localStorage.removeItem('password');
        localStorage.removeItem('rememberMe');
      }
      // 调用action的登录方法
      const [err] = await to(userStore.login(loginForm.value));
      if (!err) {
        // const redirectUrl = redirect.value || '/';
        // await router.push(redirectUrl);
        // loading.value = false;
        // 过滤 redirect 以外的 query 参数
        const query = route.query;
        const otherQueryParams = Object.keys(query).reduce((acc, cur) => {
          if (cur !== 'redirect') acc[cur] = query[cur];
          return acc;
        }, {});
        return getUserInfo(otherQueryParams);
      } else {
        loading.value = false;
        // 重新获取验证码
        if (captchaEnabled.value) {
          await getCode();
        }
      }
    } else {
      console.log('error submit!', fields);
    }
  });
};

// 获取用户信息并跳转对应首页
function getUserInfo(otherQueryParams = {}) {
  return getInfo().then((res) => {
    const role = res.data.roles?.[0] || 'ROLE_DEFAULT';
    const map = {
      superadmin: '/',
      parents: '/parents',
      egg: '/egg',
      sperm: '/sperm',
      partners: '/partners'
    };
    const path = map[role] || '/';
    router.push({ path, query: otherQueryParams });
  });
}
/**
 * 获取验证码
 */
const getCode = async () => {
  const res = await getCodeImg();
  const { data } = res;
  captchaEnabled.value = data.captchaEnabled === undefined ? true : data.captchaEnabled;
  if (captchaEnabled.value) {
    codeUrl.value = 'data:image/gif;base64,' + data.img;
    loginForm.value.uuid = data.uuid;
  }
};

const getLoginData = () => {
  const tenantId = localStorage.getItem('tenantId');
  const username = localStorage.getItem('username');
  const password = localStorage.getItem('password');
  const rememberMe = localStorage.getItem('rememberMe');
  loginForm.value = {
    tenantId: tenantId === null ? String(loginForm.value.tenantId) : tenantId,
    username: username === null ? String(loginForm.value.username) : username,
    password: password === null ? String(loginForm.value.password) : String(password),
    rememberMe: rememberMe === null ? false : Boolean(rememberMe)
  } as LoginData;
};

/**
 * 获取租户列表
 */
const initTenantList = async () => {
  const { data } = await getTenantList(false);
  tenantEnabled.value = data.tenantEnabled === undefined ? true : data.tenantEnabled;
  if (tenantEnabled.value) {
    tenantList.value = data.voList;
    if (tenantList.value != null && tenantList.value.length !== 0) {
      loginForm.value.tenantId = tenantList.value[0].tenantId;
    }
  }
};

/**
 * 第三方登录
 * @param type
 */
const doSocialLogin = (type: string) => {
  authBinding(type, loginForm.value.tenantId).then((res: any) => {
    if (res.code === HttpStatus.SUCCESS) {
      // 获取授权地址跳转
      window.location.href = res.data;
    } else {
      ElMessage.error(res.msg);
    }
  });
};

onMounted(() => {
  getCode();
  initTenantList();
  getLoginData();
});
</script>

<style lang="scss" scoped>
// 变量
$color-primary: #1e3a8a;
$color-pink: rgba(207, 112, 184, 1);
$color-gray: rgba(102, 102, 102, 1);
$bg-gray: #f9fafb;
$radius-lg: 0.5rem;
$radius-xl: 24px;

/* 1rem = 10px 便于口算 */
html {
  font-size: 62.5%;
}

.login-page {
  min-height: 100vh;
  background-color: $bg-gray;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 1rem;
}
.login-card {
  background-color: #fff;
  border-radius: $radius-lg;
  box-shadow:
    0 1rem 1.5rem -0.3rem rgba(0, 0, 0, 0.1),
    0 0.4rem 0.6rem -0.2rem rgba(0, 0, 0, 0.05);
  overflow: hidden;
  width: 100%;
  max-width: 72rem;
  display: flex;
  flex-direction: column;

  @media (min-width: 768px) {
    flex-direction: row;
  }
}
.login-form-wrapper {
  padding: 2rem;

  @media (min-width: 768px) {
    padding: 3rem;
    width: 50%;
  }
}

.site-header {
  text-align: center;
  margin-bottom: 1.5rem;
}

.logo-box {
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 1.875rem;
  font-weight: 700;
  color: $color-primary;
}

.site-title {
  font-size: 0.875rem;
  font-weight: 700;
  margin-top: 0.5rem;
}
.title-box {
  display: flex;
  align-items: center;
  justify-content: space-between;
  .form-title {
    font-size: 1.125rem;
    margin-bottom: 1.5rem;
  }
}

.divider {
  display: flex;
  gap: 0.5rem;
  margin-bottom: 1.5rem;

  .divider-short {
    height: 0.25rem;
    width: 2rem;
    background-color: $color-primary;
    border-radius: 0.25rem;
  }

  .divider-long {
    height: 0.25rem;
    flex: 1;
    background-color: $color-primary;
    border-radius: 0.25rem;
  }
}

.login-form {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.form-label {
  display: block;
  font-size: 0.875rem;
  font-weight: 700;
  color: #111827;
  margin-bottom: 0.5rem;
}

.form-input {
  ::v-deep(.el-input__wrapper) {
    border-radius: 0.375rem;
  }
  ::v-deep(.el-select__input) {
    border-radius: 0.375rem;
  }
}

.input-icon {
  color: #9ca3af;
}
.code_box {
  width: 100%;
  display: flex;
  align-items: center;
  .code_input {
    height: 38px;
    margin-right: 20px;
  }
  .login-code {
    width: 30%;
    height: 38px;
    float: right;

    img {
      width: 100%;
      height: 100%;
      cursor: pointer;
      vertical-align: middle;
    }
  }
}
.rember {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.submit-btn {
  width: 100%;
  background-color: $color-primary;
  color: #fff;
  padding: 0.5rem 0;
  border-radius: 0.5rem;
  transition: background-color 0.2s;

  &:hover {
    background-color: darken($color-primary, 10%);
  }
}

.section-divider {
  border-top: 1px solid #e5e7eb;
  margin: 1.5rem 0;
}

.extra-links {
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
  font-size: 0.875rem;
}

.link-row {
  display: flex;
  flex-wrap: wrap;
  align-items: baseline;
}

.link-text {
  color: #4b5563;
}

.link-btn {
  padding: 0;
  border: none;
  background: transparent;
  color: #2b5cab;
  height: auto;
  line-height: 1;
}

.login-bg {
  display: none;

  @media (min-width: 768px) {
    display: block;
    width: 50%;
  }

  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
}

.donor-dialog {
  ::v-deep(.el-dialog__body) {
    padding: 0;
  }
}

.donor-dialog-body {
  height: 27.8vh;
  padding: 2rem 0;
  display: flex;
  justify-content: center;
}

.donor-options {
  width: 40.8vw;
  height: 16.4vh;
  max-width: 40.8rem;
  max-height: 16.4rem;
  display: flex;
  justify-content: space-between;
  margin: auto;
}

.donor-option {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.donor-card {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 16.4vw;
  height: 16.4vw;
  max-width: 16.4rem;
  max-height: 16.4rem;
  border-radius: $radius-xl;

  &.egg {
    background-color: #fcf5f7;
  }

  &.sperm {
    background-color: #f5f5f5;
  }

  img {
    max-width: 100%;
    max-height: 100%;
  }
}

.donor-label {
  margin-top: 1.5rem;
  font-size: 1.5rem;
  font-weight: 700;
  line-height: 1.5;
  white-space: nowrap;

  &.egg {
    color: $color-pink;
  }

  &.sperm {
    color: $color-gray;
  }
}
</style>
